﻿using ch09.binary.type;

namespace ch09.binary.interpreter
{
    public struct Table
    {
        public TableType Type;
        public VmFunc[] Elems;

        public Table(TableType tt)
        {
            Type = tt;
            Elems = new VmFunc[tt.Limits.Min];
        }

        public VmFunc GetElem(uint idx)
        {
            CheckIdx(idx);
            var elem = Elems[idx];
            return elem;
        }

        public uint Size()
        {
            return (uint) (Elems.Length);
        }

        public void SetElem(uint idx, VmFunc elem)
        {
            CheckIdx(idx);
            Elems[idx] = elem;
        }

        private void CheckIdx(uint idx)
        {
            if (idx >= (uint) (Elems.Length))
            {
                Panic.Run(Errors.ErrUndefinedElem);
            }
        }
    }
}